import axios from 'axios';
import $ from "jquery";

const defaultHeader = {
    Accept: 'application/json, text/javascript, */*; q=0.01',
    Origin: 'https://y.qq.com',
    Referer: 'https://y.qq.com/portal/player.html',
    'Sec-Fetch-Mode': 'cors',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
};



const uin = '0';
var gVkey = '';
var g_tk = 123456;
var 保存的搜索文本 = '';
var 当前页码 = 1;
var 当前播放索引 = '0';

var _guid = "";
function _getGuid() {
    if (_guid.length > 0) return _guid;
    var t = (new Date).getUTCMilliseconds();
    _guid = Math.round(2147483647 * Math.random()) * t % 1e10 + '';
}
_getGuid();

class QQMusic {
    rote_list = {
        demo: {
            prefix: 'RS02',
            extension: '.mp3'
        },
        ogg: {
            prefix: 'O600',
            extension: '.ogg'
        },
        aac: {
            prefix: 'C600',
            extension: '.m4a'
        },
        m4a1: {
            prefix: 'C400',
            extension: '.m4a'
        },
        m4a: {
            prefix: 'C000',
            extension: '.m4a'
        },
        128: {
            prefix: 'M500',
            extension: '.mp3',
            br: "nq"
        },
        320: {
            prefix: 'M800',
            extension: '.mp3',
            br: "hq"
        },
        ape: {
            prefix: 'A000',
            extension: '.ape',
            br: "aq"
        },
        flac: {
            prefix: 'F000',
            extension: '.flac',
            br: "sq"
        },
        dts: {
            prefix: 'D00A',
            extension: '.flac'
        },
    }
    async getSong(mids) {
        var types = [];
        var _mids = [];
        for (var m in mids) {
            types.push(1);
            if (mids[m].mid) {
                _mids.push(mids[m].mid);
            } else {
                _mids.push(mids[m]);
            }
        }
        var fromtag = 0;
        var response = await axios({
            url: `https://u.y.qq.com/cgi-bin/musicu.fcg`,
            headers: defaultHeader,
            method: 'post',
            data: {
                req: {
                    module: "CDN.SrfCdnDispatchServer",
                    method: "GetCdnDispatch",
                    param: {
                        guid: _guid,
                        calltype: 0,
                        userip: ""
                    }
                },
                getVkey: {
                    module: 'vkey.GetVkeyServer',
                    method: 'CgiGetVkey',
                    param: {
                        guid: _guid,
                        songmid: _mids,
                        songtype: types,
                        uin: uin,
                        loginflag: 1,
                        platform: '20'
                    },
                },
                comm: {
                    uin: uin,
                    format: 'json',
                    ct: 24,
                    cv: 0,
                },
            },
        });
        var json = response.data;
        var infos = json.getVkey.data.midurlinfo;
        var urls = [];
        infos.forEach(info => {
            if (info.purl && info.purl !== '') {
                var u = '';
                if (info.purl.startsWith('http://')) {
                    u = `${info.purl}`;
                } else {
                    u = `http://isure.stream.qqmusic.qq.com/${info.purl}`;
                }
                urls.push(u);
            } else {
                var filename = info.filename;
                var smid = filename.substr(4, 14);
                var testfile2g = json.getVkey.data.testfile2g;
                var vvkey = /vkey=([^&]*)&/g.exec(testfile2g)[1];
                var key = info.vkey;
                var u = `http://isure.stream.qqmusic.qq.com/${this.rote_list[128].prefix}${smid}${this.rote_list[128].extension}?guid=${_guid}&vkey=${vvkey}&uin=${uin}&fromtag=57`;
                urls.push(u);
            }
        })
        return urls;
    }

    async getSong2(mids) {

        var rote = this.rote_list.flac;
        var names = [];
        var types = [];
        for (var m in mids) {
            names.push(`${rote.prefix}${mids[m]}${rote.extension}`);
            types.push(1);
        }
        var fromtag = 0;
        var response = await axios({
            url: `https://u.y.qq.com/cgi-bin/musicu.fcg`,
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Cookie': Cookie,
                'Host': 'u.y.qq.com',
            },
            method: 'post',
            data: {
                comm: {
                    "ct": "19",
                    "cv": "1666",
                    "patch": "118",
                    "uin": "547374673",
                    "wid": "6581539466030399488"
                },
                queryvkey: {
                    method: "CgiGetVkey",
                    module: "vkey.GetVkeyServer",
                    param: {
                        "checklimit": 0,
                        "ctx": 1,
                        "downloadfrom": 0,
                        "filename": names,
                        "guid": _guid,
                        "musicfile": names,
                        "nettype": "",
                        "referer": "y.qq.com",
                        "scene": 0,
                        songmid: mids,
                        "songtype": types,
                        "uin": "547374673"
                    }
                }
            },
        });
        var json = response.data;
        var infos = json.queryvkey.data.midurlinfo;
        var urls = [];
        if (infos && infos.length > 0) {
            infos.forEach(info => {
                var url = `http://182.247.250.18/amobile.music.tc.qq.com/${info.purl}&fromtag=${fromtag}`
                urls.push(url);
            })
        }
        console.log(urls);
        return urls;
    }

    async getSongVkey(songmid, rote = this.rote_list[128]) {
        var url = 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg'
        const params = Object.assign({}, {
            //callback: 'musicJsonCallback',
            loginUin: 3051522991,
            format: 'jsonp',
            platform: 'yqq',
            needNewCode: 0,
            cid: 205361747,
            uin: uin,
            guid: _guid,
            songmid: songmid,
            filename: `${rote.prefix}${songmid}${rote.extension}`
        })
        let paramsArray = [];
        //拼接参数  
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
        url += '?' + paramsArray.join('&');
        var response = await fetch(url, {
            headers: {
                referer: 'https://u.y.qq.com',
                host: 'u.y.qq.com'
            },
            method: 'GET',
            //body: JSON.stringify(data),
        });
        var json = await response.json();
        var item = json.data.items[0];
        if (item.vkey == '')
            console.log('没有vkey');
        else {
            var u = `http://mobileoc.music.tc.qq.com/${item.filename}?guid=${_guid}&vkey=${item.vkey}&uin=${uin}&fromtag=38`;
            console.log(u);
        }
    }

    async getSongUrl(song){
        var tUrl = "";
        if (song.file.size_flac > 0) {
          tUrl = await this.getDownloadUrl3(
            song.mid,
            this.rote_list.flac
          );
        }
        if (tUrl == "" && song.file.size_ape > 0) {
          tUrl = await this.getDownloadUrl3(song.mid, this.rote_list.ape);
        }
        if (tUrl === "" && song.file.size_320 > 0) {
          tUrl = await this.getDownloadUrl3(
            song.mid,
            this.rote_list["320"]
          );
        }
        if (tUrl === "" && song.file.size_128 > 0) {
          tUrl = await this.getDownloadUrl3(
            song.mid,
            this.rote_list["128"]
          );
        }
        return tUrl;
    }

    async getDownloadUrl3(mid, rote = this.rote_list.flac) {
        function addTo16(s) {
            if (s.length % 16 != 0) {
                var l = 16 - s.length % 16;
                for (var i = 0; i < l; i++) {
                    s += "\0";
                }
            }
            return s;
        }
        const crypto = require('crypto');
        var cc = crypto.createCipheriv("aes-128-cbc", addTo16(mid), addTo16("0o0oo0o00o0o"));
        var data = cc.update(addTo16(`{"songId":"${mid}","br":"${rote.br}"}`)).toString("hex");
        var url = `http://118.126.93.173/music/qyin_player`;
        var res = await axios({
            url: url,
            method: 'post',
            headers: {
                //'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                //'Host': 'u.y.qq.com',
            },
            data: {
                body: {
                    songId: mid,
                    data: data
                }
            }
        });
        var json = res.data;
        if (json.code == 0) {
            const 下载链接 = json.data.data;
            return 下载链接;
        } else {
            return "";
        }
    }

    async getDownloadUrl2(mid, rote = this.rote_list.flac) {
        const crypto = require('crypto');
        var br = rote.br;
        var y = mid + 'qqapi';
        var sign = crypto.createHash('md5').update(y).digest("hex");
        var url = `http://188.131.136.132/music/qqmusic?songid=${mid}&br=${br}&sign=${sign}`;
        var res = await axios({
            url: url,
            method: 'get',
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Host': 'u.y.qq.com',
            }
        });
        var json = res.data;
        if (json.msg == undefined) {
            const 前缀 = "http://dl.stream.qqmusic.qq.com/";
            const 下载链接 = `${前缀}${rote.prefix}${mid}${rote.extension}?guid=ajun&vkey=${json.data}&uin=0&fromtag=66`;
            return 下载链接;
        } else {
            return "";
        }
    }

    async getDownloadUrl(mids, rote = this.rote_list.flac) {
        var names = [];
        var types = [];
        for (var m in mids) {
            names.push(`${rote.prefix}${mids[m]}${rote.extension}`);
            types.push(1);
        }
        var fromtag = 0;
        var res = await axios({
            url: `htt://u.y.qq.com/cgi-bin/musicu.fcg`,
            method: 'post',
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                'Cookie': `qqmusic_key=${qqmusic_key}; qqmusic_uin=${qqmusic_uin}; `,
                'Host': 'u.y.qq.com',
            },
            data: {
                comm: {
                    ct: "19",
                    cv: "1666",
                    patch: "118",
                    uin: "547374673",
                    wid: ""
                },
                queryvkey: {
                    method: "CgiGetDownUrl",
                    module: "vkey.GetDownUrlServer",
                    param: {
                        "checklimit": 1,
                        "ctx": 1,
                        "downloadfrom": 0,
                        "filename": names,
                        "guid": "0",
                        "musicfile": names,
                        "nettype": "",
                        "referer": "y.qq.com",
                        "scene": 0,
                        "songmid": mids,
                        "songtype": types,
                        "uin": "547374673"
                    }
                }
            }
        });
        var json = res.data;
        var infos = json.queryvkey.data.midurlinfo;
        var urls = [];
        if (infos && infos.length > 0) {
            infos.forEach(info => {
                if (info.purl != '') {
                    var url = `http://182.247.250.18/amobile.music.tc.qq.com/${info.purl}&fromtag=${fromtag}`
                    urls.push(url);
                }
            })
        }
        return urls;
    }

    生成播放地址(songmid, vkey) {
        var url = `http://ws.stream.qqmusic.qq.com/C400${songmid}.m4a?guid=${_guid}&vkey=${vkey}&uin=${uin}&fromtag=38`;
        return url;
    }

    音乐列表 = [];

    获取歌手名称(singer) {
        var ss = [];
        for (var i in singer) {
            var s = singer[i];
            ss.push(s.title);
        }
        return ss.join(",");
    }

    async search(text, page = 1, pageSize = 20) {
        var res = await axios({
            url: `http://c.y.qq.com/soso/fcgi-bin/client_search_cp`,
            method: 'get',
            params: {
                ct: 24,
                qqmusic_ver: 1298,
                new_json: 1,
                format: 'json',
                remoteplace: 'txt.yqq.song',
                searchid: 69460324284078493,
                t: 0,
                aggr: 1,
                cr: 1,
                catZhida: 1,
                lossless: 0,
                flag_qc: 0,
                p: page,
                n: pageSize,
                w: text,
                g_tk: 'ajun',
                loginUin: 0,
                hostUin: 0,
                inCharset: 'utf8',
                outCharset: 'utf-8',
                notice: '0',
                platform: 'yqq',
                needNewCode: 0,
            }
        });
        if (res.data.data.song.list.length == 0) {
            showToast('没有搜索到歌曲？', 'danger');
            return;
        }
        var 临时列表 = [];
        var mids = [];
        for (var ii in res.data.data.song.list) {
            var song = res.data.data.song.list[ii];
            var index = 临时列表.push({
                album: song.album,
                file: song.file,
                mid: song.mid,
                id: song.id,
                name: song.title,
                singer: song.singer,
                singerText: this.获取歌手名称(song.singer),
                grp: [],
            });
            mids.push({
                mid: song.mid,
                grp: []
            });
            for (var ii1 in song.grp) {
                var song1 = song.grp[ii1];
                临时列表[index - 1].grp.push({
                    album: song1.album,
                    file: song1.file,
                    mid: song1.mid,
                    id: song1.id,
                    name: song1.title,
                    singer: song1.singer,
                    singerText: this.获取歌手名称(song.singer)
                });
                mids[index - 1].grp.push(song1.mid);
            }
        }
/*         var urls = await this.getSong(mids);
        var ind = 0;
        for (var sss in 临时列表) {
            var song = 临时列表[sss];
            song.url = urls[ind];
            var subInd = 0;
            if (song.grp.length > 0) {
                var urls1 = await this.getSong(mids[ind].grp);
                for (var sss1 in song.grp) {
                    var song1 = song.grp[sss1];
                    song1.url = urls1[subInd];
                    subInd++;
                }
            }
            ind++;
        } */
        if (page > 1) {
            this.音乐列表 = this.音乐列表.concat(临时列表);
        } else {
            this.音乐列表 = 临时列表;
        }

        var o = '';
        var index = 1;
        /* this.音乐列表.forEach(song => {
            var l = `<tr class="card-header" id="result-item" index=${index}>
                <td>${index}.</td>
                <td class='歌名'>${song.name}</td>
                <td class='歌手'>${this.获取歌手名称(song.singer)}</td>
                <td class='专辑'>${song.album.name}</td>
                <td>`;
            if (song.grp.length) l += `<a href='#result-item-sub${index}' data-toggle="collapse">+</a>`;
            l += `</td></tr>`;
            if (song.grp.length > 0) {
                var subIndex = 1;
                for (var g in song.grp) {
                    var song1 = song.grp[g];
                    var l1 = `<tr class="card-body collapse" data-parent="#songList" id="result-item-sub${index}" index="${index}.${subIndex}">
                            <td></td>
                            <td class='歌名'>${song1.name}</td>
                            <td class='歌手'>${this.获取歌手名称(song1.singer)}</td>
                            <td class='专辑'>${song1.album.name}</td>
                            </tr>`;
                    l += l1;
                    subIndex++;
                }
            }
            o += l;
            index++;
        }); */
        var result = {};
        result.关键字 = text;
        result.页大小 = pageSize;
        result.音乐列表 = this.音乐列表;
        if (page * pageSize < res.data.data.song.totalnum) {
            result.更多 = true;
        } else {
            result.更多 = false;
        }
        result.页 = page;
        return result;
    }

    dataToParams(data) {
        let paramsArray = [];
        //拼接参数  
        Object.keys(data).forEach(key => paramsArray.push(key + '=' + data[key]));
        return paramsArray.join('&');
    }

    async getLyric(musicid) {
        const data = {
            nobase64: 1,
            musicid: musicid,
            '-': 'jsonp1',
            g_tk: 5381,
            loginUin: 547374673,
            hostUin: 0,
            format: 'json',
            inCharset: 'utf8',
            outCharset: 'utf-8',
            notice: 0,
            platform: 'yqq.json',
            needNewCode: 0,
        }
        const url = `https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_yqq.fcg?${this.dataToParams(data)}`;
        var res = await axios({
            url: url,
            method: 'get',
            headers: {
                Accept: 'application/json, text/javascript, */*; q=0.01',
                //Origin: 'https://y.qq.com',
                //Referer: 'https://y.qq.com/n/yqq/song/001zZDxD3AR3pL.html',
                //'Sec-Fetch-Mode': 'cors',
                //'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
            },
        });
        var lyric = $('<div>').html(res.data.lyric).text();
        return lyric;
    }

    albumImgUrl = 'https://y.gtimg.cn/music/photo_new/T002R300x300M000 .jpg'
    singerAvatarUrl = 'https://y.gtimg.cn/music/photo_new/T001R150x150M000 .jpg'
    getAlbumImg(albummid, singerMid) {
        return {
            albumImgUrl: this.albumImgUrl.replace(/ /, albummid),
            singerAvatarUrl: this.singerAvatarUrl.replace(/ /, singerMid)
        };
    }

    trySearch() {
        保存的搜索文本 = $('#search-text').val();
        if (保存的搜索文本 == '') {
            showToast('请输入搜索内容', 'danger');
            return;
        }
        当前页码 = 1;
        this.search(保存的搜索文本, 当前页码);
    }
}

export default
    QQMusic
